package com.example.demo.game;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Wukong
 * Date: 2023-04-24
 * Time: 20:43
 */
@Component
public class RoomManager {
    //存储所有活跃的游戏房间，通过房间 ID 可以快速查找对应的房间对象
    //键 (Key)：房间 ID（String 类型）
    //值 (Value)：Room 对象
    private ConcurrentHashMap<String, Room> rooms = new ConcurrentHashMap<>();
    //记录每个用户当前所在的房间，通过用户 ID 可以快速查找其所在房间
    //键 (Key)：用户 ID（Integer 类型）
    //值 (Value)：房间 ID（String 类型）
    private ConcurrentHashMap<Integer, String> userIdToRoomId = new ConcurrentHashMap<>();
    /**
     * 创建一个新房间并将两个用户加入该房间
     * */
    public void addRoom(Room room, int userId1, int userId2) {
        rooms.put(room.getRoomId(), room);
        userIdToRoomId.put(userId1, room.getRoomId());
        userIdToRoomId.put(userId2, room.getRoomId());
    }
    /**
     * 通过房间 ID 获取对应的 Room 对象
     * */
    public Room getRoomByRoomId(String roomId) {
        return rooms.get(roomId);
    }
    /**
     * 通过用户 ID 获取其所在的房间
     * */
    public Room getRoomByUserId(int userId) {
        String roomId = userIdToRoomId.get(userId);
        if (roomId == null) {
            return null;
        }
        return getRoomByRoomId(roomId);
    }
    /**
     * 移除指定房间并解除两个用户与该房间的关联
     * */
    public void removeRoom(String roomId, int userId1, int userId2) {
        rooms.remove(roomId);
        userIdToRoomId.remove(userId1);
        userIdToRoomId.remove(userId2);
    }

    public ConcurrentHashMap<String, Room> getRooms() {
        return rooms;
    }

    public void setRooms(ConcurrentHashMap<String, Room> rooms) {
        this.rooms = rooms;
    }

    public ConcurrentHashMap<Integer, String> getUserIdToRoomId() {
        return userIdToRoomId;
    }

    public void setUserIdToRoomId(ConcurrentHashMap<Integer, String> userIdToRoomId) {
        this.userIdToRoomId = userIdToRoomId;
    }
}